package com.audaque.springboot.foshanupload.cloudauthtrans.interceptor;


import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zgb
 * @desc ...
 * @date 2022-01-26 13:51:04
 */

public class LoginMdcHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TransmittableThreadLocalCurrentUser current = TransmittableThreadLocalCurrentUser.getCurrentUser();

        /**
         * pattern		%X{}
         * 其他		${ctx:}
         */
        MDC.put("userId", current == null ? null : current.getId());
        MDC.put("username", current == null ? null : current.getUsername());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        preHandle(request, response, handler);
    }
}
